import 'package:flutter/material.dart';

import 'package:date_format/date_format.dart';

class DataTimePage extends StatefulWidget {
  DataTimePage({Key key}) : super(key: key);
  @override
  _DataTimePageState createState() => _DataTimePageState();
}

class _DataTimePageState extends State<DataTimePage> {
  //当前的日期 对象
  DateTime now = DateTime.now();

  String timeFormat =formatDate(DateTime.now(), [yyyy, '年', mm, '月', dd]);
  String timeHouseFormat =formatDate(DateTime.now(),  [HH, ':', nn]); //小时 秒 字符串

  List timeHouse = "123:456".split(':');
  TimeOfDay nowhouse = TimeOfDay(hour:12,minute: 30 );

  @override
  void initState() {
    super.initState();
    DateTime time = DateTime.parse("2019-12-15");
    this.nowhouse = TimeOfDay(hour:int.parse(timeHouseFormat.split(":")[0]),minute: int.parse(timeHouseFormat.split(":")[1]));
    print(time);
    print(formatDate(DateTime.now(), [yyyy, '年', mm, '月', dd]));
    //print(now); //2019-12-15 22:25:08.155038
    //print(this.now.millisecondsSinceEpoch);//1576419964743  获取时间戳
    //print(DateTime.fromMillisecondsSinceEpoch(1576419964743)); //2019-12-15 22:26:04.743 //时间戳  转日期对象
  }
  //Future 类似于 js promise
  _showDatePick() async{
    // showDatePicker(
    //   context: context,
    //   initialDate:DateTime.now(),
    //   firstDate:DateTime(2001),
    //   lastDate:DateTime(2110)
    // ).then((result){
    //   print(result);
    // });

    DateTime  result = await showDatePicker(
      context: context,
      initialDate:DateTime.now(),
      firstDate:DateTime(2001),
      lastDate:DateTime(2110)
    );

    print(result);
    setState(() {
      this.timeFormat = formatDate(result, [yyyy, '年', mm, '月', dd]);
    });
  }

  _showTimePick() async {
     TimeOfDay result =await  showTimePicker(
          context: context,
          initialTime: TimeOfDay(hour:12,minute: 30 )
     );
     print(result);

     setState(() {
      this.nowhouse = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("日期时间"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
            InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(this.timeFormat),
                  Icon(Icons.arrow_drop_down)
                ],
              ),
              onTap: _showDatePick,
            ),
            InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("${nowhouse.format(context)}"),
                  Icon(Icons.arrow_drop_down)
                ],
              ),
              onTap: _showTimePick,
            )
        ],
      ),
    );
  }
}
